package com.hui.auth.dao;

import com.hui.auth.dao.sql.CommonSQLProvider;
import com.hui.auth.entity.AuthPermission;
import com.hui.auth.entity.AuthUser;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

/**
 * 权限
 * Created by LiaoYunHui on 2017/9/23/023.
 */
@Mapper
public interface AuthPermissionDao {

    @InsertProvider(type = CommonSQLProvider.class, method = "insert")
    @Options(useGeneratedKeys = true)
    boolean insert(AuthPermission perm);

    /**
     * 查询所有权限
     */
    @Select("select * from auth_permission")
    List<AuthPermission> selectList(Map params);

    /**
     * 查询没有分配的权限
     */
    @Select("select * from auth_permission WHERE mid IN (-1,#{mid})")
    List<AuthPermission> selectNoUse(Map params);


    List<AuthPermission> selectActive();

    @UpdateProvider(type = CommonSQLProvider.class, method = "update")
    Integer update(AuthPermission perm);

    /**
     * 删除
     */
    @Delete("delete from auth_permission where id = #{id}")
    Integer delete(Long id);

    @Select("SELECT p.* FROM auth_user u INNER JOIN auth_user_role ur ON ur.uid = u.id INNER JOIN auth_role_permission rp ON rp.rid = ur.rid INNER JOIN auth_permission p ON rp.pid = p.id WHERE u.id = #{uid}")
    List<AuthPermission> selectByUid(long uid);

    /**
     * 根据角色rid查询权限
     */
    @Select("select p.* from auth_role_permission rp left join auth_permission p on rp.pid = p.id where rp.rid = #{rid}")
    List<AuthPermission> selectByRid(Long rid);

    /**
     * 根据角色rid查询权限IDS
     */
    @Select("select p.id from auth_role_permission rp left join auth_permission p on rp.pid = p.id where rp.rid = #{rid}")
    List<Integer> selectIdByRid(Long rid);

    /**
     * 根据角色rid查询权限（批量）
     */
    @Select("select p.* from auth_role_permission rp left join auth_permission p on rp.pid = p.id where rp.rid in (#{roleIds})")
    List<AuthPermission> selectByIds(String roleIds);

    @Select("SELECT * FROM auth_permission WHERE mid = #{mid}")
    List<AuthPermission> selectByMid(Long mid);

    /**
     * 根据角色rid删除权限
     */
    @Delete("delete from auth_role_permission where rid = #{rid}")
    int deleteByRid(long rid);

    /**
     * 根据角色rid删除权限
     */
    boolean insertRolePerms(@Param("rid") long rid, @Param("perms") List<Integer> perms);

    /**
     * 查询菜单所包含权限
     */
    @Select("SELECT id FROM auth_permission WHERE mid = #{mid}")
    List<Integer> selectPerms(Integer mid);

    /**
     * 根据PID批量修改权限
     */
    boolean updateByIds(@Param("mid") Integer mid, @Param("perms") List<Integer> perms);

    /**
     * 通过主键删除
     */
    @Delete("delete from auth_role_permission where rid = #{rid} and pid = #{pid}")
    int deleteByRidAndPid(@Param("rid") Integer rid, @Param("pid") int pid);
}
